<template>
<!--
* @Author: liuzehai
* @Motto: 求知若渴,虚心若愚
 * @LastEditTime: 2021-08-11 14:24:07
* @Description: 角色管理
 * @FilePath: /basic-services/src/views/role/role.vue
-->
  <div class="app-container">
     <div class="filter-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input class="filter-item" v-model="listQuery.roleName" placeholder="请输入角色名称" clearable></el-input>
        </el-col>
        <el-col :span="6">
          <el-input class="filter-item" v-model="listQuery.roleDesc" placeholder="请输入角色描述" clearable></el-input>
        </el-col>
        <el-col :span="6" class="filter-btn-col">
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
          <el-button type="primary" icon="el-icon-edit" v-permission="{code: 'base:role:add'}" @click="addRole">新增</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="table">
       <el-table
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column
          prop="roleName"
          label="名称"
          width="180">
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="描述">
        </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding"
        width="320">
        <template v-slot="{ row }">
          <div class="btnnuma">
            <el-button type="primary" size="small" v-permission="{code: 'base:role:update', show: row.operable == 1}" @click="Modify(row,1)">修改</el-button>
            <el-button type="danger" size="small" v-permission="{code: 'base:role:delete', show: row.operable == 1}" @click="deleteButton(row)">删除</el-button>
            <el-button type="success" size="small" @click.native.prevent="setPermissions(row)">分配资源</el-button>
          </div>
        </template>
      </el-table-column>
      </el-table>
      <pagination
        :total="totalElements"
        :page.sync="page.current"
        :limit.sync="page.size"
        @pagination="getList"
      />
    </div>
    <el-dialog
      center
      :title="updateTitle"
      width="60%"
      top="10vh"
      :visible.sync="dialogCarInfoVisible">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="22">
            <el-form-item prop="roleName" label="角色名称">
              <el-input size="small" :maxlength="30" placeholder="请输入角色名称" v-model="ruleForm.roleName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item prop="roleCode" label="角色标识">
              <el-input size="small" :maxlength="31" placeholder="请输入角色标识" v-model="ruleForm.roleCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item prop="roleDesc" label="角色描述">
              <el-input type="textarea" :rows="3" placeholder="请输入角色描述" v-model="ruleForm.roleDesc"
                :maxlength="200" :show-word-limit="true" resize="none" :autosize="{ minRows: 3, maxRows: 5 }"/>
            </el-form-item>
          </el-col>
           <el-col :span="22">
            <el-form-item prop="usable" label="数据范围">
              <el-select v-model="ruleForm.scopeType" placeholder="请选择数据范围" @change="changeValue">
                <el-option label="全部" :value="1"></el-option>
                <el-option label="自定义" :value="2"></el-option>
                <el-option label="本部门及子级" :value="3"></el-option>
                <el-option label="本部门" :value="4"></el-option>
                <el-option label="仅自己" :value="5"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
       </el-row>
      </el-form>
      <div class="tree" v-if="treeShow" ref="rangeChild">
        <el-tree
            :data="lists"
            :props="defaultProp"
            show-checkbox
            node-key="id"
            ref="rangeTreeRef"
            :check-strictly="true"
            :default-checked-keys="rangeDefaultkey">
          </el-tree>
      </div>
       <span slot="footer" class="dialog-footer">
          <el-button @click="dialogCarInfoVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit">保存</el-button>
        </span>
    </el-dialog>
     <PermissionsDialog 
     ref="child"
     @giveRules='giveRules'
     @resetDefaultKey='resetDefaultKey'
     :permissionsDialog='permissionsDialog'
      :defaultkey='defaultkey'>
    </PermissionsDialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import { role } from "@/api/account";
import { getMechanismList,getTreeByTenantIdAndGroup } from "@/api/resource";
import PermissionsDialog from "@/components/resourceDialog/permissionsDialog";
import arrayToTree from "array-to-tree"

export default {
  name: "role",
  components: { Pagination,PermissionsDialog },
  data() {
    return {
      tableData: [],
      totalElements: 0,
      rangeisCheck: false,
      updateTitle: "增加角色",
      listQuery: {
        size: 10,
        current: 1,
        roleName: "",
        roleDesc: "",
        usable: 1,
        //tenantId:this.sessionData("get","tenantId")
      },
      page: {
        current: 1,
        size: 10,
      },
      ruleForm: {
        //新增角色表单
        roleName: "", // 角色名称
        roleDesc: "", //角色描述
        roleCode: "", //角色编码
        usable: 1, //是否可用
        //tenantId:this.sessionData("get","tenantId"),
        scopeType:"", //数据类型
        deptIds:[],// 部门集合
      },
      defaultProp:{
        label: 'deptName',
        id:'id',
        parentId:'parentId'
    },
    props: {
        label: 'permissionName',
        id:'id',
        parentId:'parentId'
      },
      typeRole: 0, //判断新增还是修改角色
      roleId: "", //角色主键id
      lists: [], // 资源树
      dialogCarInfoVisible: false,
      treeShow:false,
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        roleCode: [{ required: true, message: "请输入角色标识", trigger: "blur"},{max: 30,message: "长度在 1 到 30个字符",trigger: "blur"},],
        usable: [
          { required: true, message: "请选择角色状态", trigger: "change" },
        ],
      },
      permissionsDialog: {
        show: false,
        id: ""
      },
      defaultkey: [],
      rangeDefaultkey: [],
      changeValueList: 0,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // web端获取机构数据
    getrmissionList () {
      const data = {
        group: 'web',
        //tenantId:this.sessionData("get","tenantId")
      }
      getTreeByTenantIdAndGroup(data).then(res => {
        this.lists = res.data;
        this.formatTreeData()
      })
    },
    getList() {
      const params = Object.assign(this.listQuery, this.page);
      role.getroleList(params).then((response) => {
        this.tableData = response.data.records;
        this.totalElements = response.data.total;
        this.page.current = response.data.current;
        this.page.size = response.data.size;
      });
    },
    //获取机构数据
    getrmissionList(){
      getMechanismList().then(res => {
         this.lists = arrayToTree(res.data, {
                    parentProperty: 'parentId',
                    customID: 'id'
                  });
      });
    },
    //查询
    handleFilter() {
      this.page.pageNumber = 1;
      this.getList();
    },
    // 增加角色
    addRole() {
      this.dialogCarInfoVisible = true;
      this.treeShow = false
      this.updateTitle = "增加角色";
      this.typeRole = 0;
      this.ruleForm.roleName = "";
      this.ruleForm.roleDesc = "";
      this.ruleForm.roleCode = "";
      this.ruleForm.usable = 1;
      this.ruleForm.deptIds = [];
      this.ruleForm.scopeType = "";
      this.rangeDefaultkey = [];
      delete this.ruleForm.id;
    },
    //数据范围选择
    changeValue(value){
      this.changeValueList = value
      this.rangeDefaultkey = []
      if(value == 2){
        this.treeShow = true
        this.getrmissionList()
      }else{
        this.treeShow = false
      }
    },
    //确认增加
    onSubmit() {
      if(this.changeValueList == 2){
          const keys = [...this.$refs.rangeTreeRef.getCheckedKeys(), ...this.$refs.rangeTreeRef.getHalfCheckedKeys()]
          if (keys == '') {
            keys = " "
          }
       this.ruleForm.deptIds = keys;
      }
      if (this.typeRole == 1) {
        //修改
        let params = Object.assign(this.ruleForm, { id: this.roleId });
        role.uptadeRole(params).then((res) => {
          if (res.status == 200) {
            this.dialogCarInfoVisible = false;
            this.getList();
            this.$notify({
              title: "提示",
              message: "修改成功",
              type: "success",
              duration: 2000,
            });
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
        });
      } else {
        if(this.ruleForm.usable == ""){
          this.$message({
              showClose: true,
              message: '请选择角色状态',
              type: 'error'
            });
            return
        }
        role.addrole(this.ruleForm).then((res) => {
          if (res.status == 200) {
            this.dialogCarInfoVisible = false;
            this.getList();
            this.$notify({
              title: "提示",
              message: "新增成功",
              type: "success",
              duration: 2000,
            });
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
        });
      }
    },
    // 点击分配权限按钮触发
    setPermissions(row) {
      this.roleId = row.id;
      this.permissionsDialog = {
        show: true,
        id: row.id
      }
      const queryData = {
        group: 'web',
        roleId: row.id,
        //tenantId: this.sessionData("get","tenantId")
      }
      role.getroleIDList(queryData).then((res) => {
          this.$refs.child.isCheck = true
          this.defaultkey = res.data
            setTimeout(() => {
            this.$refs.child.isCheck = false
          }, 1000);
      });
    },
    resetDefaultKey() {
      this.defaultkey = []
    },
    giveRules(menuIds) {
       const data = {
        permissionGroup: 'web',
        permissionIds: menuIds,
        //tenantId: this.sessionData("get","tenantId")
      }
      role.allotRole(this.roleId,data).then((res) => {
          if (res.status == 200) {
            this.$notify({
              title: "提示：",
              message: "分配资源成功",
              type: "success",
              duration: 2000,
            });
            this.permissionsDialog.show = false
          } else {
            this.$notify({
              title: "提示：",
              type: "error",
              message: res.msg,
              duration: 3000,
            });
          }
        });
    },
    // 修改
    Modify(scope, typeRole) {
      this.changeValueList = scope.scopeType
      if(scope.scopeType == "2"){
        this.getrmissionList()
        this.treeShow = true
        this.rangeDefaultkey = scope.deptIds
      }else{
        this.treeShow = false
      }
      this.typeRole = typeRole;
      this.roleId = scope.id;
      this.dialogCarInfoVisible = true;
      this.updateTitle = "修改角色";
      this.ruleForm.roleName = scope.roleName;
      this.ruleForm.roleDesc = scope.roleDesc;
      this.ruleForm.roleCode = scope.roleCode;
      this.ruleForm.usable = scope.usable;
      this.ruleForm.scopeType = scope.scopeType;
    },
    //删除按钮
    deleteButton(scope) {
      this.$confirm(
        "删除角色,拥有该角色的账号将无法查看相关菜单页,是否继续?",
        "删除角色",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          role.deleteRole(scope.id).then((res) => {
            if (res.status == 200) {
              this.$notify({
                title: "提示：",
                message: "删除角色成功",
                type: "success",
                duration: 2000,
              });
              this.getList();
            } else {
              this.$notify({
                title: "提示：",
                type: "error",
                message: res.msg,
                duration: 3000,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //禁用按钮
    disablebtn(scope) {
      if (scope.usable == "1") {
        this.$confirm(
          "禁用该角色,相关账号登陆只能查看首页, 是否继续?",
          "角色状态",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            role.toggleRole(scope.id).then((res) => {
              if (res.status == 200) {
                this.$notify({
                  title: "提示：",
                  message: "禁用角色成功",
                  type: "success",
                  duration: 2000,
                });
                this.getList();
              } else {
                this.$notify({
                  title: "提示：",
                  type: "error",
                  message: res.msg,
                  duration: 3000,
                });
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消禁用",
            });
          });
      } else {
        this.$confirm(
          "启用该角色,相关账号登陆只能查看相应资源菜单, 是否继续?",
          "角色状态",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            role.toggleRole(scope.id).then((res) => {
              if (res.status == 200) {
                this.$notify({
                  title: "提示：",
                  message: "启用成功",
                  type: "success",
                  duration: 2000,
                });
                this.getList();
              } else {
                this.$notify({
                  title: "提示：",
                  type: "error",
                  message: res.msg,
                  duration: 3000,
                });
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消启用",
            });
          });
      }
    },
  },
  watch: {},
};
</script>


<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
@import "~@/styles/variables.scss";

.box {
  padding: 0 15px;
}

.el-row {
  margin-bottom: 25px;
  &:last-child {
    margin-bottom: 0;
  }
}

.form-item {
  display: flex;
  font-size: 16px;

  > .label {
    margin: 0;
    line-height: 1;
    white-space: nowrap;
    padding-right: 12px;
  }
}
.btnnuma {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}
.card {
  display: flex;
  justify-content: space-around;
  .tablebox {
    flex: 2;
    margin-right: 5px;
  }
  .jigou {
    flex: 2;
    height: 100%;
  }
}
.tree{
  padding-left: 50px;
}
</style>
